<template>
  <Form autocomplete="off" class="user-form" ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
    <Row  :gutter="24" type="flex">
     <Col span="5">
      <h3>{{isAdd?'新增护栏':'编辑护栏'}}</h3>
      <FormItem   class="project mt20" label="所属项目" prop="projectId" >
        <Select :disabled="!isAdd" v-model="formValidate.projectId" >
          <Option v-for="item in list" :value="item.id" :key="item.id">{{ item.name }}</Option>
        </Select>
      </FormItem>
       <FormItem label="护栏名称" prop="name" >
         <Input :disabled="!isAdd"  name="name"  v-model="formValidate.name" placeholder="请输入护栏名称"></Input>
       </FormItem>
       <FormItem class="time"   label="创建时间" prop="installDate" >
         <DatePicker  format="yyyy-MM-dd HH:mm:ss"  :value="formValidate.installDate" type="date" @on-change="changeTime"  placeholder="选择日期" ></DatePicker>
         <input type="hidden"  v-model="formValidate.installDate" />
       </FormItem>
       <FormItem label="护栏地址" prop="address" class="addrees-list"  style="z-index: 9999;position: relative;">
         <Input v-model="formValidate.address"   placeholder="请输入护栏地址" @on-change="getAddress"></Input>
         <ul class="address-con">
           <li :key="o.id" v-for="o in adressList" @click="getaddessValue(o)">
             {{o.name}}
           </li>
         </ul>
       </FormItem>
       <FormItem label="护栏描述" prop="bz">
         <Input v-model="formValidate.bz" type="textarea"  placeholder="请输入护栏描述"></Input>
       </FormItem>
       <div class="ivu-text-center mt30">
         <Button  @click="handleSubmit('formValidate')">提交</Button>
       </div>
     </Col>
     <Col span="19" style="height: calc(100vh - 80px)">
       <FormItem label=""  prop="position" class="position">
         <div  class="pop-position">
           <autoMap style="height: calc(100vh - 80px)" :editorId="formValidate.id" :forbid="forbid"   :isDraw="isDraw" :mapInfo="mapInfo"  @getDrawPath="getDrawPath" ref="autoMap"></autoMap>
           <input type="hidden" style="height:0px;opacity: 0" v-model="formValidate.position"  placeholder="请输入护栏描述"></input>
         </div>
       </FormItem>
    </Col>
    </Row>


  </Form>
</template>
<script>
import {railAdd,railUpdate,railList} from '@/api/device';
import autoMap from "@/components/Map/autoMap";
import tool from "@/libs/tool";
import {address} from  "@/api/base";
import setting from '../../setting'
import moment from "moment";

export default {
  components:{autoMap},
  created() {
    this.getData();
  },
  computed:{
    forbid:function (){
      return this.deviceCount>0?true:false;
    }
  },
  props:{
    deviceCount:{
      type:Number,
      default:0,

    },
    list:{
      type:Array,
      default:()=>{
        return []
      }
    },
    orgList:{
      type:Array,
      default:()=>{
        return []
      }
    },
    isAdd:{
      type:Boolean,
      default:true,
    },
    editorData:{
      type:Object,
      default:()=>{
        return {};
      }
    },
  },
  watch:{
    isAdd(newdata,oldData){
        this.init();
    }
  },
  mounted() {
    this.init()
  },
  data () {
    return {
      editorId:'',
      adressList:[],
      orgData:[],
      mapInfo:[],//护栏地图落点的信息
      isDraw:true,//是否开启绘图
      positionFlag:false,
      pwdType:'text',
      formValidate: {
        name:'',
        installDate:'',
        bz:'',
        address:'',
        id:'',
        projectId:'',
        position:'',
      },
      ruleValidate: {
        position: [
          { required: true,  message: '地图位置不能为空', trigger: 'change' },
        ],
        projectId: [
          { required: true,  message: '护栏所属项目不能为空', trigger: 'change' },
        ],
        name: [
          { required: true, message: '护栏名称不能为空', trigger: 'blur' },
          { max: 100, message: '护栏名称长度不能超过100个字符', trigger: 'blur' },
        ],
        address: [
          { max: 100, message: '护栏地址长度不能超过100个字符', trigger: 'blur' },
        ],
        bz: [
          { max: 255, message: '护栏备注长度不能超过255个字符', trigger: 'blur' },
        ],
        // installDate: [
        //   { message: '护栏创建时间不能为空', trigger: 'blur' },
        // ],
      }
    }
  },
  methods: {
    getaddessValue(item){
      this.formValidate.address=item.name;
    },
    changeTime(time){
      this.formValidate.installDate=time
    },
    async getAddress(value){
      console.log(value,'=====console====')
      let res = await address({
        key:setting.map_server_key,
        keywords:this.formValidate.address,
      })
      this.adressList=_.get(res,'tips')||[];
    },
    init(){
      console.log(this.editorData,'this.editorData')
      this.formValidate=this.isAdd?{
        name:'',
        installDate:moment().format('YYYY-MM-DD HH:mm:ss'),
        bz:'',
        address:'',
        id:'',
        projectId:'',
        position:'',
      }:{...this.editorData};
      console.log(this.editorData,'====')

      // this.mapInfo=tool.fromatMapInfo([this.formValidate]);
    },
    async getData(){
      let res =await railList({orgIds:this.orgIds});
      this.mapInfo=tool.fromatMapInfo(_.get(res,'data.records')||[]);

    },
    getSumbitParm(){
      return {
        ...this.formValidate,
        installDate:moment(this.formValidate.installDate).format("YYYY-MM-DD hh:mm:ss")
      }
    },
    getDrawPath(data){//获取地图绘制的地理坐标
      console.log(data,'==data==')
      this.formValidate.position=this.formatPostion(data);
      this.formValidate.id=this.formValidate.id||''+(new Date).getTime();
      if(this.mapInfo.findIndex(o=>o.id==data.id)==-1){
        this.mapInfo=this.mapInfo.concat(tool.fromatMapInfo([this.formValidate]))
      }
      // this.mapInfo=tool.fromatMapInfo([this.formValidate]);
    },
    formatPostion(arr=[]) {
      let path=[];
      arr.map(item=>{
        path.push(item.lng+','+item.lat);
      })
      return JSON.stringify(path);
    },
    async Add(){
      return  await railAdd(this.getSumbitParm());
    },
    async updata(){
      return await railUpdate(this.getSumbitParm())
    },
    handleSubmit (name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
        let res = this.isAdd? await this.Add():await this.updata();
          if(_.get(res,'code')==0){
            this.$Message.success(this.isAdd?'新增成功':'修改成功');
            this.$emit('success');
          }else{
            this.$Message.error(_.get(res,'message'));
          }

        } else {
          // this.$Message.error('Fail!');
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields();
    }
  }
}
</script>
<style scoped lang="less">
.pop-position{
  //height:400px;
}
.addrees-list{
  position: relative;
  z-index: 99999;
  &:hover{
    .address-con{
      display: block;
    }
  }
  .address-con{
    position: absolute;
    left: 0;
    top: 32px;
    background: #fff;
    border: 1px solid #eee;
    max-height:200px;
    overflow-y:auto ;
    overflow-x: hidden;
    display: none;
    li{
      cursor:pointer;
      padding: 0 10px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      &:hover{
        background: #eee;
      }
    }

  }
}
/deep/.project{
  .ivu-select-dropdown{
    z-index: 99999;
  }
}
/deep/ .position{
  .ivu-form-item-content{
    margin-left:0px !important;
  }
}
/deep/ .time{
  .ivu-date-picker .ivu-select-dropdown{
    z-index:10000;
  }
}
</style>
